package geowiki.data;

import geowiki.utils.ClientHttpRequest;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import processing.core.PApplet;
import processing.xml.XMLElement;

public class PlacemakerPlaceExtractor extends PlaceExtractor {
	
	public static final String PLACEMAKER_API_URL = "http://wherein.yahooapis.com/v1/document";
	public static final String DOCUMENT_TYPE = "text/html";
	public static final String APP_ID = "ZBmjABTV34GeruUFtXI7x0zRvm1saOC.kU1vCBwIy8g6joYqK0NcHdGjupbo";
	
	public PlacemakerPlaceExtractor(PApplet p) {
		super(p);
	}

	public List<Place> getPlacesFromURL(String url) {
		throw new UnsupportedOperationException();
	}

	public List<Place> getPlaces(String content) {

		try {
			ClientHttpRequest clientHttpRequest = new ClientHttpRequest(PLACEMAKER_API_URL);

			clientHttpRequest.setParameter("documentContent", content);
			clientHttpRequest.setParameter("documentType", DOCUMENT_TYPE);
			clientHttpRequest.setParameter("appId", APP_ID);

			InputStream is = clientHttpRequest.post();
			Reader r = PApplet.createReader(is);

			XMLElement xmlResponse = new XMLElement(r);
			return getPlacesFromXmlResponse(xmlResponse);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	private List<Place> getPlacesFromXmlResponse(XMLElement xmlResponse) {
		List<Place> places = new ArrayList<Place>();
		XMLElement[] placeXMLElements = xmlResponse.getChildren("document/placeDetails/place");
		for (int i = 0; i < placeXMLElements.length; i++) {
			String name = placeXMLElements[i].getChild(2).getContent();
			//PApplet.println(i + ". name=" + name);
			float lat = new Float(placeXMLElements[i].getChild(3).getChild(0).getContent());
			//PApplet.println(i + ". lat=" + lat);
			float lng = new Float(placeXMLElements[i].getChild(3).getChild(1).getContent());

			Place place = new Place(name, lat, lng);
			places.add(place);
		}

		return places;
	}


}
